package org.example.config;

import lombok.extern.slf4j.Slf4j;
import org.example.enums.BizCodeEnum;
import org.example.exception.BizException;
import org.springframework.context.annotation.Configuration;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @description:
 * @author: 谢超
 * @date: 2023/8/14 15:46
 */
@Configuration
@Slf4j
public class SnowFlakeWordIdConfig {

    /**
     * 动态指定sharding jdbc 的雪花算法中的属性work.id属性
     * 通过调⽤System.setProperty()的方式实现，可用容器的id 或者机器标识位
     * workId最⼤值 1L << 100，就是1024，即 0<= workId < 1024
     * {@link SnowflakeShardingKeyGenerator#getWorkerId()}
     */
    static {
        try {
            InetAddress localHost = Inet4Address.getLocalHost();

            String hostIp = localHost.getHostAddress();

            String workId = Math.abs(hostIp.hashCode()) % 1024 + "";

            System.setProperty("workId", workId);

        }catch (UnknownHostException e) {
            throw new BizException(BizCodeEnum.OPS_NETWORK_ADDRESS_ERROR);
        }
    }
}
